package m.html.element;

import m.html.element.other.IElement;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Element implements IElement {
	private final String tagName;

	public Element(String tagName) {
		this.tagName=tagName;
		this.attrs=new HashMap<>();
		this.elementList=new ArrayList<>();
	}
	/**
	 * 静态构造方法
	 *  tagName
	 * 
	 */
	public static Element tag(String tagName) {
		return new Element(tagName);
	}
	/**
	 * 属性
	 */
	private final Map<String,String> attrs;
	/**
	 * 添加属性 简写
	 *  name
	 *  value
	 * 
	 */
	public Element A(String name,String value) {
		attrs.put(name,value);
		return this;
	}
	/**
	 * 添加属性 简写
	 *  name
	 * 
	 */
	public Element A(String name) {
		return A(name,null);
	}
	/**
	 * 获取属性值
	 */
	public String getAttr(String name) {
		return attrs.get(name);
	}
	public Element delAttr(String name) {
		this.attrs.remove(name);
		return this;
	}
	/**
	 * 子元素列表
	 */
	private final List<IElement> elementList;
	public List<IElement> getChilds(){
		return this.elementList;
	}
	/**
	 * 添加子元素
	 *  element
	 * 
	 */
	public Element E(IElement... element) {
		if(null!=element) {
			for(IElement e : element) {
				if(null!=e) this.elementList.add(e);
			}
		}
		return this;
	}
	/**
	 * 添加元素数组
	 *  elements
	 * 
	 */
	public <T extends IElement> Element E(List<T> elements) {
		if(null!=elements) this.elementList.addAll(elements);
		return this;
	}
	private String extend="";
	/**
	 * 设置扩展属性
	 *  extend
	 * 
	 */
	public Element setExtend(String extend) {
		this.extend=extend;
		return this;
	}

	@Override
	public String toString() {
		StringBuilder sb=new StringBuilder();
		sb.append("<").append(this.tagName).append(" ");
		for(String k : this.attrs.keySet()) {
			if(null==this.attrs.get(k)) 
				sb.append(k).append(" ");
			else
				sb.append(k).append("=\"").append(this.attrs.get(k)).append("\" ");
		}
		sb.append(extend).append(this.elementList.size()==0?"/":"").append(">");
		if(this.elementList.size()>0) {
			for (IElement ele : this.elementList) {
				sb.append(ele);
			}
			sb.append("</").append(this.tagName).append(">");
		}
		return sb.toString();
	}
}
